package com.jzqf.harmonydemo.ability.slice;

import com.jzqf.harmonydemo.ResourceTable;
import com.jzqf.harmonydemo.base.BaseAbilitySlice;
import com.jzqf.harmonydemo.library.database.entity.UserEntity;
import com.jzqf.harmonydemo.library.database.helper.UserHelper;
import com.jzqf.harmonydemo.utils.JsonUtil;
import com.jzqf.harmonydemo.utils.LogUtil;
import ohos.aafwk.content.Intent;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class DatabaseAbilitySlice extends BaseAbilitySlice {
    private final String TAG = DatabaseAbilitySlice.class.getSimpleName();

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setTitle("database");
        initView();
    }

    @Override
    protected int getLayoutResId() {
        return ResourceTable.Layout_ability_database;
    }

    private void initView() {
        findComponentById(ResourceTable.Id_database_insert_btn).setClickedListener(component -> {
            UserEntity userEntity = new UserEntity();
            Random random = new Random();
            userEntity.setUserNo(random.nextInt(10000));
            userEntity.setUserName("江沨");
            UserHelper.insert(userEntity);
        });
        findComponentById(ResourceTable.Id_database_delete_btn).setClickedListener(component -> {
            UserHelper.deleteByName("江沨");
        });
        findComponentById(ResourceTable.Id_database_deleteAll_btn).setClickedListener(component -> {
            UserHelper.deleteAll();
        });
        findComponentById(ResourceTable.Id_database_update_btn).setClickedListener(component -> {
            if (UserHelper.queryAll().size() == 0) {
                return;
            }
            UserEntity userEntity = UserHelper.queryAll().get(0);
            userEntity.setUserName(userEntity.getUserName() + "_update");
            UserHelper.update(userEntity);
        });
        findComponentById(ResourceTable.Id_database_batchInsert_btn).setClickedListener(component -> {
            List<UserEntity> list = new ArrayList<>();
            Random random = new Random();
            for (int i = 0; i < 1000; i++) {
                UserEntity userEntity = new UserEntity();
                userEntity.setUserNo(random.nextInt(10000));
                userEntity.setUserName("江沨" + i);
                list.add(userEntity);
            }
            UserHelper.inserts(list);
        });
        findComponentById(ResourceTable.Id_database_query_btn).setClickedListener(component -> {
            List<UserEntity> userEntities = UserHelper.queryAll();
            LogUtil.d(TAG, "size=" + userEntities.size() + ","
                    + JsonUtil.toJson(userEntities));
        });
    }


    @Override
    protected void onStop() {
        super.onStop();
    }
}
